import { Tag, Input, Icon } from 'antd';
import React, { useState, useRef, useEffect } from 'react';

const EditableTagGroup = ({ value = [], onChange, label = '标签', disabled }) => {
    const [tags, setTags] = useState([]);
    const [inputVisible, setInputVisible] = useState(false);
    const [inputValue, setInputValue] = useState('');
    const inputEl = useRef(null);

    useEffect(() => {
        if (inputVisible) {
            inputEl.current.focus();
        }
    }, [inputVisible]);

    const handleClose = removedTag => {
        const t = tags.filter(tag => tag !== removedTag);
        setTags(t);
        if (onChange) {
            onChange(t);
        }
    };

    const showInput = () => {
        setInputVisible(true);
    };

    const handleInputChange = e => {
        setInputValue(e.target.value);
    };

    const handleInputConfirm = () => {
        let t = tags;
        if (inputValue && tags.indexOf(inputValue) === -1) {
            t = [...tags, inputValue];
        }
        if (onChange) {
            onChange(t);
        }
        setTags(t);
        setInputVisible(false);
        setInputValue('');
    };

    useEffect(() => {
        if (value?.length > 0) {
            setTags(value);
        }
    }, [value]);

    const forMap = tag => {
        const tagElem = (
            <Tag
                closable={!disabled}
                onClose={e => {
                    e.preventDefault();
                    handleClose(tag);
                }}
            >
                {tag}
            </Tag>
        );
        return (
            <span key={tag} style={{ display: 'inline-block' }}>
                {tagElem}
            </span>
        );
    };

    return (
        <>
            {tags.map(forMap)}
            {inputVisible && (
                <Input
                    maxLength={20}
                    disabled={disabled}
                    ref={inputEl}
                    type="text"
                    size="small"
                    style={{ width: 78 }}
                    value={inputValue}
                    onChange={handleInputChange}
                    onBlur={handleInputConfirm}
                    onPressEnter={handleInputConfirm}
                />
            )}
            {!inputVisible && !disabled && (
                <Tag onClick={showInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
                    <Icon type="plus" /> {label}
                </Tag>
            )}
        </>
    );
};

export default EditableTagGroup;
